<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class MigrationUsersData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migration:users';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migration origin database users data to new databases';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
    	DB::connection('mozhu')->table('users')
			->select([
				'users.id',
				'user_basic_infos.name',
				'gender', 'birthday', 'number',
				'users.companyid', 'users.departments',
				'users.project_id', 'users.username',
				'users.type',
				'users.created_at',
				'users.updated_at',
				'users.deleted_at',
			])
			->leftJoin('user_basic_infos', 'users.id', '=', 'user_id')
			->orderBy('users.id')->groupBy('users.username')
			->chunk(100, function ($users) {
				$usersAttributes = [];
				foreach ($users as $user) {
					$usersAttributes[] = [
						'name' => $user->name,
						'mobile' => $user->username,
						'password' => bcrypt('111111'),
						'birthday' => $user->birthday,
						'gender' => $user->gender,
						'identification' => null,
						'company_id' => $user->companyid,
						'department_id' => $user->departments,
						'project_id' => $user->project_id,
						'position_id' => $user->type,
						'avatar' => '',
						'certificate' => '',
						'manager' => 0,
						'created_at' => $user->created_at,
						'updated_at' => $user->updated_at,
						'deleted_at' => $user->deleted_at,
					];
				}
				DB::table('users')->insert($usersAttributes);
			});
    	$this->info('Success migration');
    }
}
